#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
智能指令处理服务

集成指令解析和执行功能，提供完整的自然语言到系统操作的转换
"""

import json
import time
from typing import Dict, List, Optional, Any

# 处理相对导入和直接运行的兼容性
try:
    from .command_parser import CommandParser
    from .command_executor import CommandExecutor
except ImportError:
    from command_parser import CommandParser
    from command_executor import CommandExecutor


class IntelligentCommandService:
    """
    智能指令处理服务
    
    将用户的自然语言输入转换为系统操作，包括：
    1. 指令解析：使用LLM分析自然语言
    2. 指令验证：验证解析结果的有效性
    3. 指令执行：执行具体的系统操作
    4. 结果反馈：提供执行结果和状态
    """
    
    def __init__(self):
        """初始化智能指令服务"""
        self.parser = CommandParser()
        self.executor = CommandExecutor()
        
        # 执行历史记录
        self.execution_history = []
        
        print("🤖 智能指令处理服务已启动")
    
    def process_command(self, user_input: str, options: Dict[str, Any] = None) -> Dict[str, Any]:
        """
        处理用户指令
        
        Args:
            user_input: 用户的自然语言输入
            options: 可选配置参数
                - dry_run: 只解析不执行 (默认False)
                - confidence_threshold: 置信度阈值 (默认0.5)
                - save_history: 是否保存历史记录 (默认True)
                
        Returns:
            处理结果，包含解析和执行信息
        """
        start_time = time.time()
        
        if options is None:
            options = {}
        
        dry_run = options.get("dry_run", False)
        confidence_threshold = options.get("confidence_threshold", 0.5)
        save_history = options.get("save_history", True)
        
        try:
            print(f"\n🎯 处理用户指令: {user_input}")
            print("=" * 60)
            
            # 第一步：解析指令
            print("📋 步骤1: 解析自然语言指令...")
            parsed_result = self.parser.parse_command(user_input)
            
            if parsed_result.get("error"):
                return self._create_final_result(
                    user_input=user_input,
                    parsed_command=parsed_result,
                    execution_result=None,
                    success=False,
                    message="指令解析失败",
                    processing_time=time.time() - start_time
                )
            
            # 第二步：验证指令
            print("✅ 步骤2: 验证指令有效性...")
            if not self.parser.validate_command(parsed_result):
                return self._create_final_result(
                    user_input=user_input,
                    parsed_command=parsed_result,
                    execution_result=None,
                    success=False,
                    message="指令验证失败：不支持的指令类型或参数",
                    processing_time=time.time() - start_time
                )
            
            # 第三步：检查置信度
            confidence = parsed_result.get("confidence", 0)
            if confidence < confidence_threshold:
                return self._create_final_result(
                    user_input=user_input,
                    parsed_command=parsed_result,
                    execution_result=None,
                    success=False,
                    message=f"指令理解置信度过低 ({confidence:.2f} < {confidence_threshold})",
                    processing_time=time.time() - start_time
                )
            
            print(f"🎯 指令解析成功: {parsed_result['intent']} -> {parsed_result['action']} (置信度: {confidence:.2f})")
            
            # 第四步：执行指令（如果不是dry run模式）
            execution_result = None
            if not dry_run:
                print("⚡ 步骤3: 执行系统操作...")
                execution_result = self.executor.execute_command(parsed_result)
                
                if execution_result.get("success"):
                    print(f"✅ 执行成功: {execution_result.get('message')}")
                else:
                    print(f"❌ 执行失败: {execution_result.get('error')}")
            else:
                print("🔍 Dry Run模式: 跳过实际执行")
                execution_result = {
                    "success": True,
                    "message": "Dry Run模式 - 未实际执行",
                    "error": None
                }
            
            # 创建最终结果
            final_result = self._create_final_result(
                user_input=user_input,
                parsed_command=parsed_result,
                execution_result=execution_result,
                success=execution_result.get("success", False),
                message="指令处理完成",
                processing_time=time.time() - start_time
            )
            
            # 保存历史记录
            if save_history:
                self._save_to_history(final_result)
            
            return final_result
            
        except Exception as e:
            print(f"❌ 指令处理失败: {e}")
            return self._create_final_result(
                user_input=user_input,
                parsed_command=None,
                execution_result=None,
                success=False,
                message=f"处理过程中发生错误: {str(e)}",
                processing_time=time.time() - start_time
            )
    
    def batch_process_commands(self, commands: List[str], options: Dict[str, Any] = None) -> List[Dict[str, Any]]:
        """
        批量处理多个指令
        
        Args:
            commands: 指令列表
            options: 处理选项
            
        Returns:
            处理结果列表
        """
        print(f"📦 开始批量处理 {len(commands)} 个指令...")
        
        results = []
        for i, command in enumerate(commands, 1):
            print(f"\n--- 处理第 {i}/{len(commands)} 个指令 ---")
            result = self.process_command(command, options)
            results.append(result)
        
        print(f"\n📊 批量处理完成，成功: {sum(1 for r in results if r['success'])} / {len(results)}")
        return results
    
    def get_supported_commands(self) -> Dict[str, Any]:
        """获取支持的指令类型"""
        return self.parser.get_supported_commands()
    
    def get_execution_history(self, limit: int = 10) -> List[Dict[str, Any]]:
        """
        获取执行历史记录
        
        Args:
            limit: 返回记录数量限制
            
        Returns:
            历史记录列表
        """
        return self.execution_history[-limit:] if limit > 0 else self.execution_history
    
    def clear_history(self):
        """清空执行历史"""
        self.execution_history.clear()
        print("🗑️ 执行历史已清空")
    
    def get_statistics(self) -> Dict[str, Any]:
        """获取使用统计信息"""
        if not self.execution_history:
            return {
                "total_commands": 0,
                "success_rate": 0,
                "most_used_intents": {},
                "average_processing_time": 0
            }
        
        total = len(self.execution_history)
        successful = sum(1 for record in self.execution_history if record["success"])
        
        # 统计最常用的意图
        intent_counts = {}
        total_time = 0
        
        for record in self.execution_history:
            if record.get("parsed_command") and record["parsed_command"].get("intent"):
                intent = record["parsed_command"]["intent"]
                intent_counts[intent] = intent_counts.get(intent, 0) + 1
            
            total_time += record.get("processing_time", 0)
        
        return {
            "total_commands": total,
            "success_rate": successful / total if total > 0 else 0,
            "most_used_intents": dict(sorted(intent_counts.items(), key=lambda x: x[1], reverse=True)),
            "average_processing_time": total_time / total if total > 0 else 0
        }
    
    def _create_final_result(self, user_input: str, parsed_command: Optional[Dict[str, Any]], 
                           execution_result: Optional[Dict[str, Any]], success: bool, 
                           message: str, processing_time: float) -> Dict[str, Any]:
        """创建最终结果对象"""
        return {
            "user_input": user_input,
            "success": success,
            "message": message,
            "processing_time": processing_time,
            "timestamp": time.time(),
            "parsed_command": parsed_command,
            "execution_result": execution_result
        }
    
    def _save_to_history(self, result: Dict[str, Any]):
        """保存到历史记录"""
        self.execution_history.append(result)
        
        # 限制历史记录数量，避免内存占用过多
        max_history = 100
        if len(self.execution_history) > max_history:
            self.execution_history = self.execution_history[-max_history:]


def main():
    """测试和演示函数"""
    service = IntelligentCommandService()
    
    # 测试用例
    test_commands = [
        "你好，请帮我播放周杰伦的稻香",
        "帮我写一篇关于人工智能的小说",
        "打开我电脑上的文本编辑器",
        "创建一个新的文本文件叫做test.txt",
        "暂停音乐播放"
    ]
    
    print("🧪 开始测试智能指令处理服务...")
    print("=" * 80)
    
    # 单个指令测试
    for i, command in enumerate(test_commands, 1):
        print(f"\n🔬 测试 {i}: {command}")
        print("-" * 60)
        
        result = service.process_command(command)
        
        print(f"\n📋 处理结果:")
        print(f"  成功: {result['success']}")
        print(f"  消息: {result['message']}")
        print(f"  处理时间: {result['processing_time']:.2f}秒")
        
        if result.get('parsed_command'):
            parsed = result['parsed_command']
            print(f"  解析结果: {parsed['intent']} -> {parsed['action']} (置信度: {parsed['confidence']:.2f})")
        
        if result.get('execution_result'):
            exec_result = result['execution_result']
            if exec_result['success']:
                print(f"  执行结果: ✅ {exec_result['message']}")
            else:
                print(f"  执行结果: ❌ {exec_result['error']}")
        
        print("=" * 60)
    
    # 显示统计信息
    print(f"\n📊 使用统计:")
    stats = service.get_statistics()
    print(f"  总指令数: {stats['total_commands']}")
    print(f"  成功率: {stats['success_rate']:.2%}")
    print(f"  平均处理时间: {stats['average_processing_time']:.2f}秒")
    print(f"  最常用意图: {stats['most_used_intents']}")
    
    # Dry Run测试
    print(f"\n🔍 Dry Run模式测试:")
    dry_result = service.process_command("播放音乐", {"dry_run": True})
    print(f"  结果: {dry_result['success']} - {dry_result['message']}")


if __name__ == "__main__":
    main()
